package com.heima.common.exception;


import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice  //控制器增强类
@Slf4j
public class ExceptionCatch {

    /**
     * 处理不可控异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
//    @ResponseBody
    public ResponseResult exception(Exception e){
        e.printStackTrace();
        log.error("catch exception:{}",e.getMessage());

        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 处理可控异常  自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
//    @ResponseBody
    public ResponseResult exception(CustomException e){
        log.error("catch exception:{}",e);
        if(StringUtils.isBlank(e.getMsg())){
            return ResponseResult.errorResult(e.getAppHttpCodeEnum());
        }else{
            return ResponseResult.errorResult(e.getAppHttpCodeEnum(),e.getMsg());
        }

    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult method(MethodArgumentNotValidException e){
        log.error("catch exception:",e);
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        for (ObjectError error : allErrors) {
//            sb.append(((FieldError) error).getField());
            sb.append(error.getDefaultMessage());
            sb.append(" ");
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,sb.toString());
    }
}
